package longcaisuyun.longcai.com.yiliubabalongcaisuyun;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.secret.SecretAESDESede;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import longcaisuyun.longcai.com.mystatic.publicUrl;
import longcaisuyun.longcai.com.mystatic.publicstatic;
import longcaisuyun.longcai.com.net.GetCardType;
import longcaisuyun.longcai.com.suyunbean.CardLeiXingBean;
import longcaisuyun.longcai.com.utils.TimeCount;
import longcaisuyun.longcai.com.utils.Tools;



//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//         佛祖保佑             永无BUG
//         佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
/************************************************************/
//
/************************************************************/

/**
 * 添加银行卡
 */
public class AddCardActivity extends Activity implements View.OnClickListener {
    PopupWindow popupWindow;
    Button bt_next;
    LinearLayout lin_wl;

    TextView textView84;
    List<CardLeiXingBean> list = new ArrayList<>();
    EditText editText;
    EditText editText_1;
    EditText editText_4;
    EditText editText_5;
    Button button2;
    String code;
    TimeCount timeCount;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_card);
        View view = getWindow().getDecorView();
        // 适配工具将视图重新排布
        MyApplication.ScaleScreenHelper.loadView((ViewGroup) view);
        ViewInit();
        publicstatic.list_mima.add(this);
        HttpGet();

    }

    private void HttpGet() {
        MyApplication.myviewutil.startProgressDialog(AddCardActivity.this);
        new GetCardType(new AsyCallBack<GetCardType.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetCardType.Info info) throws Exception {
                super.onSuccess(toast, type, info);
                if (info.message.equals("1")) {
                    for (int j = 0; j < info.list.size(); j++) {
                        list.add(info.list.get(j));
                    }
                }
                MyApplication.myviewutil.stopProgressDialog();
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                MyApplication.myviewutil.stopProgressDialog();
            }
        }).execute(AddCardActivity.this);
    }

    private void ViewInit() {
        LinearLayout   fanhui_lin= (LinearLayout) findViewById(R.id.fanhui_lin);
        fanhui_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        editText = (EditText) findViewById(R.id.editText);
        editText_1 = (EditText) findViewById(R.id.editText_1);
        editText_4 = (EditText) findViewById(R.id.editText_4);
        editText_5 = (EditText) findViewById(R.id.editText_5);
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(this);
        bt_next = (Button) findViewById(R.id.bt_next);
        bt_next.setOnClickListener(this);
        lin_wl = (LinearLayout) findViewById(R.id.lin_wl);
        lin_wl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopUp();
            }
        });
        textView84 = (TextView) findViewById(R.id.textView84);
    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_next:


                if (TextUtils.isEmpty(editText.getText().toString().trim())){
                    Toast.makeText(AddCardActivity.this, "持卡人不能为空", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(editText_1.getText().toString().trim())) {
                    Toast.makeText(AddCardActivity.this, "卡号不能为空", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(textView84.getText().toString())){
                    Toast.makeText(AddCardActivity.this, "卡类型不能为空", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(editText_4.getText().toString().trim())){
                    Toast.makeText(AddCardActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(editText_5.getText().toString().trim())){
                    Toast.makeText(AddCardActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                }


               else if (textView84.getText().length() > 0 && editText.getText().length() > 0 && editText_1.getText().length() > 0 && editText_4.getText().length() > 0 && editText_5.getText().length() > 0) {
                    if (!checkBankCard(editText_1.getText().toString())) {
                        Toast.makeText(AddCardActivity.this, "卡号填写错误", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    if (!Tools.isMobile(editText_4.getText().toString())) {
                        Toast.makeText(AddCardActivity.this, "手机号填写错误", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    if (!editText_5.getText().toString().equals(code)) {
                        Toast.makeText(AddCardActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                        break;
                    }

                    Intent intent = new Intent();
                    intent.setClass(AddCardActivity.this, SzmmActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("name", editText.getText().toString());
                    bundle.putString("num", editText_1.getText().toString());
                    bundle.putString("type", textView84.getText().toString());
                    bundle.putString("mobile", editText_4.getText().toString());
                    //跳页识别
                    bundle.putString("model","3");
                    intent.putExtras(bundle);
                    AddCardActivity.this.startActivity(intent);
                } else {
                    Toast.makeText(AddCardActivity.this, "填写资料不全", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.button2:

                if (editText_4.getText().toString().length() > 0) {
                    if (Tools.isMobile(editText_4.getText().toString())) {
                        httpPost(editText_4.getText().toString(), "3");
                    } else {
                        Toast.makeText(AddCardActivity.this, "输入的手机号码格式错误，请检查后重新输入", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(AddCardActivity.this, "您还未输入手机号码", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    private void showPopUp() {

        View view = View.inflate(AddCardActivity.this, R.layout.pop_wl, null);
        MyApplication.ScaleScreenHelper.loadView((ViewGroup) view);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(lin_wl);
        ListView l = (ListView) view.findViewById(R.id.listView9);
        l.setAdapter(new WLadapter());
        l.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {

                textView84.setText(list.get(arg2).getTitle());

                popupWindow.dismiss();
            }
        });
    }

    public class WLadapter extends BaseAdapter {

        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(AddCardActivity.this, R.layout.item_pop_wl, null);
            MyApplication.ScaleScreenHelper.loadView((ViewGroup) view);
            TextView t = (TextView) view.findViewById(R.id.textView1);
            t.setText(list.get(position).getTitle());
            return view;
        }


    }

    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId
                .substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }

    private static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null
                || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    private void httpPost(String mobile, String action) {
        final SecretAESDESede secretAESDESede = new SecretAESDESede("123456781234567812345678", "12345678", SecretAESDESede.DESEDE_CBC_PKCS5PADDING);
        final FinalHttp finalHttp = new FinalHttp();
        AjaxParams params = new AjaxParams();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile", mobile);
            jsonObject.put("action", action);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            params.put("Keys", secretAESDESede.encrypt(jsonObject.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }


        finalHttp.post(publicUrl.mobilecode, params, new AjaxCallBack<String>() {


            public void onStart() {
                super.onStart();
                MyApplication.myviewutil.startProgressDialog(AddCardActivity.this, finalHttp, publicUrl.mobilecode);
            }

            public void onSuccess(String s) {
                super.onSuccess(s);

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(secretAESDESede.decrypt(s));
                    Log.e("什么鬼", jsonObject.toString());
                    String Message = jsonObject.getString("message");
                    if (Message.equals("1") || Message.equals("2")) {
                        timeCount = new TimeCount(60000, 1000, button2);
                        timeCount.start();
                        code = jsonObject.getString("code");
                    }

                    if (Message.equals("0")) {
                        Toast.makeText(AddCardActivity.this, "获取验证码失败，请重新获取", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }catch (Exception e) {
                    e.printStackTrace();
                }
                MyApplication.myviewutil.stopProgressDialog();
            }

            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                MyApplication.myviewutil.stopProgressDialog();
            }
        });
    }
}
